import { Inject, Injectable, OnModuleInit } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { MqttClient } from 'mqtt';
import { MQTT_SUBSCRIBE_CLIENT_PROVIDER } from '../constants/mqtt.constant';

@Injectable()
export class MqttSubscribeService implements OnModuleInit {
  constructor(
    @Inject(MQTT_SUBSCRIBE_CLIENT_PROVIDER)
    private readonly mqttSubscribeClient: MqttClient,
    private readonly eventEmitter: EventEmitter2
  ) {}

  onModuleInit() {
    this.subscribe();
    this.messageHandler();
  }

  /** 订阅Topic */
  private subscribe() {
    // TODO: 订阅主题
    // this.mqttSubscribeClient.subscribe('$queue/jx_iot/+/+/msg_cloud_up/+', { qos: 1 });
  }

  /** 消息处理 */
  private messageHandler() {
    this.mqttSubscribeClient.on('connect', packet => console.log(packet));

    this.mqttSubscribeClient.on('message', (topic, payload) => this.eventEmitter.emit(topic, payload, topic));
    // this.mqttSubscribeClient.on('message', (topic, payload) => {
    //   console.log(topic);
    //   this.eventEmitter.emit(topic, payload, topic);
    // });

    this.mqttSubscribeClient.on('disconnect', packet => console.log(packet));

    this.mqttSubscribeClient.on('error', error => console.log(error.stack));
  }
}
